package com.example.alarm;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

import java.text.MessageFormat;
import java.util.Calendar;

public class MainActivity extends Activity implements TimePicker.OnTimeChangedListener {

    String text;
    private AlarmManager am = null;
    private TimePicker tpTime;
    public static final String ACTION_ALARM = "com.book.action.set_alarm";
    PendingIntent sender;
    private Calendar calendar = Calendar.getInstance();
    private int hourOfDay = 0;
    private int minute = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_activity);
        tpTime = (TimePicker)super.findViewById(R.id.tp_time);
        tpTime.setIs24HourView(true);
        tpTime.setOnTimeChangedListener(this);
        Intent i = new Intent(MainActivity.this,AlarmReceiver.class);
        i.setAction(ACTION_ALARM);


        sender = PendingIntent.getBroadcast(MainActivity.this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
        hourOfDay = tpTime.getCurrentHour();
        minute = tpTime.getCurrentMinute();
    }

    public void clickSet(View view){
        am =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),sender);
        Object[]args = {hourOfDay,minute};
        if(hourOfDay<10){
            args[0] = "0" +hourOfDay;
        }
        if (minute<10){
            args[1] = "0" +minute;
        }
        text = MessageFormat.format("闹钟时间：{0}时{1}分，如果需要删除请马上点击删除闹钟按钮",args);
        Toast.makeText(MainActivity.this,text,Toast.LENGTH_LONG).show();

    }


    public void clickDel(View view){
        if (am != null){
            am.cancel(sender);
            am = null;
            text ="闹钟删除成功";
            Toast.makeText(MainActivity.this,text,Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
        calendar.set(Calendar.MINUTE,minute);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);


    }
}